import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由配置规则
import routes from './routes'
// 导入store中的token数据
import store from '../store'

Vue.use(VueRouter)

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

/**
 * 访问控制：登录过才能访问某些页面
 */
/**
 * to =>去哪
 * form =>从哪来
 * next=>通行证
 */
router.beforeEach((to, form, next) => {
  // 获取token
  const { user } = store.state; const loginConfig = { path: '/login', query: { redirectUrl: to.path } }
  if (to.path.startsWith('/user') && !user.token) {
    // 没有登录=》不能访问=》跳到登录
    next(loginConfig)
  } else {
    next()
  }
})

export default router
